<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人信息</title>
    <script src="/home/js/jquery-3.5.1.js"></script>
    <script src="/home/js/vue.js"></script>
    <script src="/home/js/axios.js"></script>
    <script src="/home/js/config.js"></script>
    <style>
        /* 基础样式 */
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: Arial, "Microsoft YaHei", sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f5f7fa;
        }

        /* 面包屑导航 */
        .breadcrumb {
            padding: 10px 20px;
            background-color: #f8f9fa;
            font-size: 14px;
            color: #666;
        }

        .breadcrumb a {
            color: #409eff;
            text-decoration: none;
        }

        .breadcrumb a:hover {
            text-decoration: underline;
        }

        .breadcrumb span {
            margin: 0 5px;
            color: #999;
        }

        /* 主容器 */
        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 0 20px;
        }

        /* 信息展示区域 */
        .info-section {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }

        .info-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 15px;
            border-bottom: 1px solid #ebeef5;
            margin-bottom: 20px;
        }

        .info-title {
            font-size: 18px;
            font-weight: 600;
            color: #303133;
        }

        .edit-btn {
            background-color: #409eff;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 8px 16px;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.3s;
            display: block;
        }

        .edit-btn:hover {
            background-color: #66b1ff;
        }

        /* 信息项 */
        .info-item {
            display: flex;
            padding: 12px 0;
            border-bottom: 1px solid #f0f2f5;
            align-items: center;
        }

        .info-item:last-child {
            border-bottom: none;
        }

        .info-label {
            width: 120px;
            font-weight: 500;
            color: #606266;
            flex-shrink: 0;
        }

        .info-value {
            flex: 1;
            color: #303133;
        }

        /* 模态框样式 */
        .mask {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .bj {
            background: #fff;
            border-radius: 8px;
            width: 500px;
            max-width: 90%;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            animation: slideDown 0.3s ease;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .bj_title {
            padding: 20px;
            border-bottom: 1px solid #ebeef5;
            font-size: 16px;
            font-weight: 500;
            color: #303133;
        }

        .bj_nei {
            padding: 20px;
        }

        .form-item {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #606266;
        }

        .form-input {
            width: 100%;
            padding: 10px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .form-input:focus {
            outline: none;
            border-color: #409eff;
        }

        .form-input.valid {
            border-color: #67c23a;
        }

        .form-input.invalid {
            border-color: #f56c6c;
        }

        .error-msg {
            color: #f56c6c;
            font-size: 12px;
            margin-top: 4px;
        }

        .success-msg {
            color: #67c23a;
            font-size: 12px;
            margin-top: 4px;
        }

        .loading-msg {
            color: #909399;
            font-size: 12px;
            margin-top: 4px;
        }

        .bj_anniu {
            display: flex;
            justify-content: flex-end;
            padding: 15px 20px;
            border-top: 1px solid #ebeef5;
        }

        .btn {
            padding: 8px 16px;
            border-radius: 4px;
            border: none;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .btn-primary {
            background-color: #409eff;
            color: white;
            margin-left: 10px;
        }

        .btn-primary:hover:not(:disabled) {
            background-color: #66b1ff;
        }

        .btn-primary:disabled {
            background-color: #a0cfff;
            cursor: not-allowed;
        }

        .btn-default {
            background-color: #fff;
            border: 1px solid #dcdfe6;
            color: #606266;
        }

        .btn-default:hover {
            border-color: #c0c4cc;
            color: #409eff;
        }
    </style>
</head>
<body>
<!-- 页面头部 -->
<div id="header"></div>

<!-- 面包屑导航 -->
<div class="breadcrumb">
    <a href="/home/index.html">首页</a>
    <span>></span>
    <span>个人信息</span>
</div>

<div class="container">
    <h2>个人信息</h2>
    <hr>

    <!-- 基本信息 -->
    <div class="info-section">
        <div class="info-header">
            <h3 class="info-title">基本信息</h3>
            <button class="edit-btn" @click="openEditModal">编辑</button>
        </div>

        <div class="info-item">
            <div class="info-label">用户名：</div>
            <div class="info-value">{{ user.username }}</div>
        </div>

        <div class="info-item">
            <div class="info-label">姓名：</div>
            <div class="info-value">{{ user.realName }}</div>
        </div>

        <div class="info-item">
            <div class="info-label">联系电话：</div>
            <div class="info-value">{{ user.phone }}</div>
        </div>

        <div class="info-item">
            <div class="info-label">电子邮箱：</div>
            <div class="info-value">{{ user.email }}</div>
        </div>

        <div class="info-item">
            <div class="info-label">证件类型：</div>
            <div class="info-value">{{ getCardTypeText(user.cardType) }}</div>
        </div>

        <div class="info-item">
            <div class="info-label">用户类型：</div>
            <div class="info-value">{{ getUserTypeText(user.userType) }}</div>
        </div>

        <div class="info-item">
            <div class="info-label">注册时间：</div>
            <div class="info-value">{{ formatDate(user.registerTime) }}</div>
        </div>
        <div class="info-item">
            <div class="info-label">人脸注册：</div>
            <div class="info-value">
                <span v-if="user.faceRegister === 1" style="color: #67c23a;">✓ 已注册</span>
                <span v-else style="color: #f56c6c;">✗ 未注册</span>
            </div>
        </div>
        <div class="info-item">
            <div class="info-label">人脸操作：</div>
            <div class="info-value">
                <button v-if="user.faceRegister === 0" class="edit-btn" @click="openFaceRegisterModal">
                    人脸注册
                </button>
                <button v-else class="edit-btn" @click="openFaceRegisterModal">
                    更改人脸信息
                </button>
            </div>
        </div>
    </div>

    <!-- 编辑模态框 -->
    <div v-if="showEditModal" class="mask" @click.self="closeEditModal">
        <div class="bj">
            <div class="bj_title">编辑个人信息</div>
            <div class="bj_nei">
                <div class="form-item">
                    <label class="form-label">用户名：</label>
                    <input
                            type="text"
                            class="form-input"
                            v-model="editForm.username"
                            @input="validateUsername"
                            :class="{ 'valid': validated.username && !errorMsg.username, 'invalid': errorMsg.username }"
                    >
                    <div v-if="loading.username" class="loading-msg">正在验证...</div>
                    <div v-else-if="errorMsg.username" class="error-msg">{{ errorMsg.username }}</div>
                    <div v-else-if="validated.username" class="success-msg">用户名可用</div>
                </div>

                <div class="form-item">
                    <label class="form-label">联系电话：</label>
                    <input
                            type="text"
                            class="form-input"
                            v-model="editForm.phone"
                            @input="validatePhone"
                            :class="{ 'valid': validated.phone && !errorMsg.phone, 'invalid': errorMsg.phone }"
                    >
                    <div v-if="loading.phone" class="loading-msg">正在验证...</div>
                    <div v-else-if="errorMsg.phone" class="error-msg">{{ errorMsg.phone }}</div>
                    <div v-else-if="validated.phone" class="success-msg">手机号可用</div>
                </div>

                <div class="form-item">
                    <label class="form-label">电子邮箱：</label>
                    <input
                            type="text"
                            class="form-input"
                            v-model="editForm.email"
                            @input="validateEmail"
                            :class="{ 'valid': validated.email && !errorMsg.email, 'invalid': errorMsg.email }"
                    >
                    <div v-if="loading.email" class="loading-msg">正在验证...</div>
                    <div v-else-if="errorMsg.email" class="error-msg">{{ errorMsg.email }}</div>
                    <div v-else-if="validated.email" class="success-msg">邮箱可用</div>
                </div>
            </div>
            <div class="bj_anniu">
                <button class="btn btn-default" @click="closeEditModal">取消</button>
                <button class="btn btn-primary" @click="submitForm" :disabled="!canSubmit">保存</button>
            </div>
        </div>
    </div>

    <!-- 人脸注册模态框 -->
    <div v-if="showFaceRegisterModal" class="mask" @click.self="closeFaceRegisterModal">
        <div class="bj" style="width: 600px;">
            <div class="bj_title">{{ user.faceRegister === 0 ? '人脸注册' : '更新人脸信息' }}</div>
            <div class="bj_nei">
                <!-- 密码验证步骤 -->
                <div v-if="!passwordVerified" class="form-item">
                    <label class="form-label">请输入密码验证身份：</label>
                    <input
                            type="password"
                            class="form-input"
                            v-model="passwordForm.password"
                            placeholder="请输入登录密码"
                            @keyup.enter="verifyPassword"
                    >
                    <div v-if="passwordError" class="error-msg">{{ passwordError }}</div>
                    <div v-if="passwordLoading" class="loading-msg">验证中...</div>
                </div>

                <!-- 图片上传步骤 -->
                <div v-else class="form-item">
                    <label class="form-label">请选择人脸照片：</label>

                    <!-- 选择方式 -->
                    <div v-if="!faceImage && !showCamera" style="margin-bottom: 15px;">
                        <button class="btn btn-primary" @click="selectImage" style="margin-right: 10px;">
                            上传图片
                        </button>
                        <button class="btn btn-default" @click="startCamera">
                            拍照
                        </button>
                        <p style="margin-top: 10px; color: #909399; font-size: 12px;">
                            请选择清晰的人脸照片，建议使用证件照
                        </p>
                    </div>

                    <!-- 隐藏的文件输入 -->
                    <input
                        type="file"
                        id="faceImageInput"
                        accept="image/*"
                        @change="handleImageUpload"
                        style="display: none;"
                    >

                    <!-- 摄像头显示区域 -->
                    <div v-if="isCameraVisible" style="border: 1px dashed #dcdfe6; padding: 20px; text-align: center; border-radius: 4px; margin-bottom: 10px;">
                        <video id="cameraVideo" autoplay muted playsinline style="max-width: 100%; max-height: 200px; border-radius: 4px; background-color: #f5f5f5;"></video>
                        <div style="margin-top: 10px;">
                            <button class="btn btn-primary" @click="capturePhoto" :disabled="cameraLoading">
                                {{ cameraLoading ? '拍照中...' : '拍照' }}
                            </button>
                            <button class="btn btn-default" @click="stopCamera" style="margin-left: 10px;">
                                取消拍照
                            </button>
                        </div>
                        <p style="margin-top: 10px; color: #909399; font-size: 12px;">
                            请确保面部清晰可见，照片质量良好
                        </p>
                    </div>

                    <!-- 图片预览区域 -->
                    <div v-if="faceImage" style="border: 1px dashed #dcdfe6; padding: 20px; text-align: center; border-radius: 4px; margin-bottom: 10px;">
                        <img :src="'data:image/jpeg;base64,' + faceImage" style="max-width: 100%; max-height: 200px; border-radius: 4px;">
                        <div style="margin-top: 10px;">
                            <button class="btn btn-default" @click="clearImage">重新选择</button>
                        </div>
                    </div>

                    <div v-if="imageError" class="error-msg">{{ imageError }}</div>
                    <div v-if="imageLoading" class="loading-msg">上传中...</div>
                </div>
            </div>
            <div class="bj_anniu">
                <button class="btn btn-default" @click="closeFaceRegisterModal">取消</button>
                <button
                    v-if="!passwordVerified"
                    class="btn btn-primary"
                    @click="verifyPassword"
                    :disabled="!passwordForm.password || passwordLoading"
                >
                    验证密码
                </button>
                <button
                    v-else
                    class="btn btn-primary"
                    @click="submitFaceRegister"
                    :disabled="!faceImage || imageLoading"
                >
                    {{ imageLoading ? '上传中...' : '确认注册' }}
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 页面底部 -->
<div id="footer"></div>
<script></script>

<script>
    // 等待DOM加载完成
    document.addEventListener('DOMContentLoaded', function () {
        // 创建Vue实例
        var app = new Vue({
            el: '.container',
            data: {
                user: {
                    username: 'face',
                    realName: 'FACE_LOGIN',
                    phone: '13800138000',
                    email: 'example@domain.com',
                    cardType: 0,
                    cardNum: '110101199001011234',
                    userType: 0,
                    registerTime: '2023-01-01 00:00:00',
                    user_id: '1'
                },
                editForm: {
                    username: '',
                    phone: '',
                    email: '',
                    user_id: ''
                },
                showEditModal: false,
                errorMsg: {
                    username: '',
                    phone: '',
                    email: ''
                },
                validated: {
                    username: false,
                    phone: false,
                    email: false
                },
                loading: {
                    username: false,
                    phone: false,
                    email: false
                },
                // 防抖定时器
                debounceTimers: {
                    username: null,
                    phone: null,
                    email: null
                },
                // 人脸注册相关数据
                showFaceRegisterModal: false,
                passwordForm: {
                    password: ''
                },
                passwordVerified: false,
                passwordError: '',
                passwordLoading: false,
                faceImage: '',
                imageError: '',
                imageLoading: false,
                // 摄像头相关数据
                showCamera: false,
                cameraStream: null,
                cameraLoading: false
            },
            computed: {
                // 判断是否可以提交
                canSubmit: function () {
                    return this.validated.username &&
                        this.validated.phone &&
                        this.validated.email &&
                        !this.errorMsg.username &&
                        !this.errorMsg.phone &&
                        !this.errorMsg.email;
                },
                // 摄像头可见性状态
                isCameraVisible: function () {
                    return this.showCamera && !this.faceImage;
                }
            },
            mounted: function () {
                this.loadUserInfo();
                this.loadHeaderFooter();
            },
            methods: {
                // 加载用户信息
                loadUserInfo: function () {
                    // 从localStorage获取USER_ID
                    const userId = localStorage.getItem('USER_ID');

                    if (!userId) {
                        alert('未找到用户信息，请重新登录');
                        return;
                    }

                    console.log('正在加载用户信息，用户ID：', userId);

                    // 使用axios调用后端接口获取用户信息
                    axios.get('/home/getUserInfo', {
                        params: {
                            userId: parseInt(userId)
                        }
                    })
                        .then(response => {
                            const data = response.data;

                            // 检查接口返回是否成功
                            if (data.code === 200 && data.data) {
                                const userData = data.data;
                                // 将用户数据正确映射并回显到页面
                                this.user = {
                                    username: userData.username || '',
                                    realName: userData.name || '', // 映射name到realName
                                    phone: userData.phone || '',
                                    email: userData.email || '',
                                    cardType: 0, // 后端未提供，使用默认值
                                    cardNum: '', // 后端未提供
                                    userType: 0, // 后端未提供，使用默认值
                                    registerTime: userData.createTime || '', // 映射createTime到registerTime
                                    user_id: userData.userId.toString() || '', // 映射userId到user_id
                                    faceRegister: userData.faceRegister || 0 // 映射faceRegister字段
                                };
                                console.log('用户信息加载成功', this.user);
                            } else {
                                console.error('获取用户信息失败：', data.message || '未知错误');
                                alert('获取用户信息失败，请稍后重试');
                            }
                        })
                        .catch(error => {
                            console.error('请求用户信息失败：', error);
                            alert('网络请求失败，请检查网络连接');
                        });
                },

                // 打开编辑模态框
                openEditModal: function () {
                    // 复制用户信息到编辑表单
                    this.editForm.username = this.user.username;
                    this.editForm.phone = this.user.phone;
                    this.editForm.email = this.user.email;
                    this.editForm.user_id = this.user.user_id;

                    // 重置验证状态
                    this.resetValidation();

                    // 显示模态框
                    this.showEditModal = true;
                },

                // 重置验证状态
                resetValidation: function () {
                    this.errorMsg.username = '';
                    this.errorMsg.phone = '';
                    this.errorMsg.email = '';
                    this.validated.username = false;
                    this.validated.phone = false;
                    this.validated.email = false;
                    this.loading.username = false;
                    this.loading.phone = false;
                    this.loading.email = false;

                    // 清除防抖定时器
                    for (let key in this.debounceTimers) {
                        if (this.debounceTimers[key]) {
                            clearTimeout(this.debounceTimers[key]);
                            this.debounceTimers[key] = null;
                        }
                    }
                },

                // 关闭编辑模态框
                closeEditModal: function () {
                    this.showEditModal = false;
                },

                // 验证用户名 - 使用axios调用后端接口
                validateUsername: function () {
                    // 清除之前的定时器
                    if (this.debounceTimers.username) {
                        clearTimeout(this.debounceTimers.username);
                    }

                    // 设置新的定时器，防抖处理
                    this.debounceTimers.username = setTimeout(() => {
                        const username = this.editForm.username.trim();

                        // 先进行格式验证
                        if (!username) {
                            this.errorMsg.username = '请输入用户名';
                            this.validated.username = false;
                            return;
                        }

                        // 如果是当前用户的原始用户名，直接通过验证
                        if (username === this.user.username) {
                            this.errorMsg.username = '';
                            this.validated.username = true;
                            return;
                        }

                        // 显示加载状态
                        this.loading.username = true;
                        this.errorMsg.username = '';
                        this.validated.username = false;

                        // 使用axios调用后端接口检查用户名是否存在
                        axios.get('/home/checkUserName', {
                            params: {
                                username: username
                            }
                        })
                            .then(response => {
                                this.loading.username = false;
                                const data = response.data;

                                // 根据后端接口返回判断：success()表示用户名存在，fail()表示不存在
                                if (data.code === 200) { // 假设200表示success()
                                    this.errorMsg.username = '用户名已存在';
                                    this.validated.username = false;
                                } else { // fail()表示用户名不存在，可以使用
                                    this.validated.username = true;
                                }
                            })
                            .catch(error => {
                                this.loading.username = false;
                                this.errorMsg.username = '验证失败，请稍后重试';
                                console.error('验证用户名失败', error);
                            });
                    }, 1500); // 1500ms防抖延迟
                },

                // 验证手机号 - 使用axios调用后端接口
                validatePhone: function () {
                    // 清除之前的定时器
                    if (this.debounceTimers.phone) {
                        clearTimeout(this.debounceTimers.phone);
                    }

                    // 设置新的定时器，防抖处理
                    this.debounceTimers.phone = setTimeout(() => {
                        const phone = this.editForm.phone.trim();
                        const phoneRegex = /^1[3-9]\d{9}$/;

                        // 先进行格式验证
                        if (!phone) {
                            this.errorMsg.phone = '请输入手机号';
                            this.validated.phone = false;
                            return;
                        }

                        if (!phoneRegex.test(phone)) {
                            this.errorMsg.phone = '手机号格式不正确';
                            this.validated.phone = false;
                            return;
                        }

                        // 如果是当前用户的原始手机号，直接通过验证
                        if (phone === this.user.phone) {
                            this.errorMsg.phone = '';
                            this.validated.phone = true;
                            return;
                        }

                        // 显示加载状态
                        this.loading.phone = true;
                        this.errorMsg.phone = '';
                        this.validated.phone = false;

                        // 使用axios调用后端接口检查手机号是否存在
                        axios.get('/home/checkPhone', {
                            params: {
                                phone: phone
                            }
                        })
                            .then(response => {
                                this.loading.phone = false;
                                const data = response.data;

                                // 根据后端接口返回判断
                                if (data.code === 200) { // 假设200表示success()
                                    this.errorMsg.phone = '手机号已被使用';
                                    this.validated.phone = false;
                                } else { // fail()表示手机号不存在，可以使用
                                    this.validated.phone = true;
                                }
                            })
                            .catch(error => {
                                this.loading.phone = false;
                                this.errorMsg.phone = '验证失败，请稍后重试';
                                console.error('验证手机号失败', error);
                            });
                    }, 500);
                },

                // 验证邮箱 - 使用axios调用后端接口
                validateEmail: function () {
                    // 清除之前的定时器
                    if (this.debounceTimers.email) {
                        clearTimeout(this.debounceTimers.email);
                    }

                    // 设置新的定时器，防抖处理
                    this.debounceTimers.email = setTimeout(() => {
                        const email = this.editForm.email.trim();
                        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

                        // 先进行格式验证
                        if (!email) {
                            this.errorMsg.email = '请输入邮箱';
                            this.validated.email = false;
                            return;
                        }

                        if (!emailRegex.test(email)) {
                            this.errorMsg.email = '邮箱格式不正确';
                            this.validated.email = false;
                            return;
                        }

                        // 如果是当前用户的原始邮箱，直接通过验证
                        if (email === this.user.email) {
                            this.errorMsg.email = '';
                            this.validated.email = true;
                            return;
                        }

                        // 显示加载状态
                        this.loading.email = true;
                        this.errorMsg.email = '';
                        this.validated.email = false;

                        // 使用axios调用后端接口检查邮箱是否存在
                        axios.get('/home/checkEmail', {
                            params: {
                                email: email
                            }
                        })
                            .then(response => {
                                this.loading.email = false;
                                const data = response.data;

                                // 根据后端接口返回判断
                                if (data.code === 200) { // 假设200表示success()
                                    this.errorMsg.email = '邮箱已被使用';
                                    this.validated.email = false;
                                } else { // fail()表示邮箱不存在，可以使用
                                    this.validated.email = true;
                                }
                            })
                            .catch(error => {
                                this.loading.email = false;
                                this.errorMsg.email = '验证失败，请稍后重试';
                                console.error('验证邮箱失败', error);
                            });
                    }, 500);
                },

                // 提交表单
                submitForm: function () {
                    // 确保所有字段都已验证通过
                    if (!this.canSubmit) {
                        alert('请确保所有信息都已正确填写');
                        return;
                    }

                    if (confirm('确认要提交修改么？')) {
                        // 确保editForm中包含必要的user_id
                        if (!this.editForm.user_id) {
                            alert('用户信息不完整，请刷新页面重试');
                            return;
                        }

                        // 创建提交数据对象，确保字段名与后端匹配
                        const submitData = {
                            username: this.editForm.username,
                            phone: this.editForm.phone,
                            email: this.editForm.email,
                            userId: this.editForm.user_id // 这里修改为userId字段名
                        };

                        // 使用axios提交数据到后端
                        axios.post('/home/updateUserInfo', submitData)
                            .then(response => {
                                const data = response.data;
                                if (data.code === 200) {
                                    alert('修改成功！');
                                    this.closeEditModal();
                                    // 更新本地用户信息
                                    this.user.username = this.editForm.username;
                                    this.user.phone = this.editForm.phone;
                                    this.user.email = this.editForm.email;
                                } else {
                                    alert('修改失败：' + (data.message || '未知错误'));
                                }
                            })
                            .catch(error => {
                                console.error('提交修改失败', error);
                                alert('网络请求失败，请检查网络连接');
                            });
                    }
                },

                // 获取证件类型文本
                getCardTypeText: function (cardType) {
                    const cardTypes = {
                        0: '居民身份证',
                        1: '港澳居民居住证',
                        2: '台湾居民居住证',
                        3: '外国人永久居留身份证',
                        4: '外国护照',
                        5: '中国护照',
                        6: '港澳居民来往内地通行证',
                        7: '台湾居民来往大陆通行证'
                    };
                    return cardTypes[cardType] || '未知类型';
                },

                // 获取用户类型文本
                getUserTypeText: function (userType) {
                    const userTypes = {
                        0: '普通用户',
                        1: '学生用户',
                        2: '军人用户',
                        3: '残疾人用户'
                    };
                    return userTypes[userType] || '普通用户';
                },

                // 格式化日期
                formatDate: function (dateString) {
                    if (!dateString) return '';
                    const date = new Date(dateString);
                    if (isNaN(date.getTime())) return dateString;
                    return date.getFullYear() + '-' +
                        String(date.getMonth() + 1).padStart(2, '0') + '-' +
                        String(date.getDate()).padStart(2, '0');
                },

                // 加载header和footer
                loadHeaderFooter: function () {
                    // 尝试使用jQuery加载
                    if (typeof $ !== 'undefined') {
                        $('#header').load('/home/header.html');
                        $('#footer').load('/home/footer.html');
                    } else {
                        // 如果jQuery不可用，使用原生方法
                        this.loadHTML('/home/header.html', 'header');
                        this.loadHTML('/home/footer.html', 'footer');
                    }
                },

                // 原生方法加载HTML
                loadHTML: function (url, elementId) {
                    fetch(url)
                        .then(response => response.text())
                        .then(html => {
                            document.getElementById(elementId).innerHTML = html;
                        })
                        .catch(error => {
                            console.error('加载' + elementId + '失败', error);
                        });
                },

                // ========== 人脸注册相关方法 ==========

                // 打开人脸注册模态框
                openFaceRegisterModal: function () {
                    this.resetFaceRegisterForm();
                    this.showFaceRegisterModal = true;
                },

                // 关闭人脸注册模态框
                closeFaceRegisterModal: function () {
                    this.showFaceRegisterModal = false;
                    this.resetFaceRegisterForm();
                },

                // 重置人脸注册表单
                resetFaceRegisterForm: function () {
                    this.passwordForm.password = '';
                    this.passwordVerified = false;
                    this.passwordError = '';
                    this.passwordLoading = false;
                    this.faceImage = '';
                    this.imageError = '';
                    this.imageLoading = false;
                    // 停止并清理摄像头
                    this.stopCamera();
                    this.cameraLoading = false;
                },

                // 验证密码
                verifyPassword: function () {
                    if (!this.passwordForm.password) {
                        this.passwordError = '请输入密码';
                        return;
                    }

                    this.passwordLoading = true;
                    this.passwordError = '';

                    // 验证密码逻辑，修改为使用URL参数方式以匹配后端@RequestParam
                    const params = new URLSearchParams();
                    params.append('userId', this.user.user_id);
                    params.append('password', this.passwordForm.password);

                    axios.post('/home/verifyPassword?' + params.toString())
                    .then(response => {
                        this.passwordLoading = false;
                        const data = response.data;

                        if (data.code === 200) {
                            this.passwordVerified = true;
                        } else {
                            this.passwordError = '密码错误，请重新输入';
                        }
                    })
                    .catch(error => {
                        this.passwordLoading = false;
                        console.error('密码验证失败', error);
                        this.passwordError = '验证失败，请稍后重试';
                    });
                },

                // 处理图片上传
                handleImageUpload: function (event) {
                    const file = event.target.files[0];

                    if (!file) {
                        return;
                    }

                    // 验证文件类型
                    if (!file.type.startsWith('image/')) {
                        this.imageError = '请选择图片文件';
                        return;
                    }

                    // 验证文件大小（限制5MB）
                    if (file.size > 5 * 1024 * 1024) {
                        this.imageError = '图片大小不能超过5MB';
                        return;
                    }

                    this.imageError = '';
                    this.imageLoading = true;

                    // 转换为Base64
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        // 去掉data:image/jpeg;base64,前缀，只保留base64部分
                        const base64 = e.target.result.split(',')[1];
                        this.faceImage = base64;
                        this.imageLoading = false;
                    };
                    reader.onerror = () => {
                        this.imageError = '图片读取失败';
                        this.imageLoading = false;
                    };
                    reader.readAsDataURL(file);
                },

                // 清除图片
                clearImage: function () {
                    this.faceImage = '';
                    document.getElementById('faceImageInput').value = '';
                },

                // 提交人脸注册
                submitFaceRegister: function () {
                    if (!this.faceImage) {
                        this.imageError = '请选择人脸照片';
                        return;
                    }

                    this.imageLoading = true;
                    this.imageError = '';

                    // 构建请求数据
                    const faceData = {
                        image: this.faceImage,
                        userInfo: JSON.stringify({
                            userId: this.user.user_id,
                            username: this.user.username,
                            name: this.user.realName
                        }),
                        userId: this.user.user_id,
                        groupId: 'login_face_1'
                    };

                    // 调用后端人脸注册接口
                    axios.post('/home/faceRegister', faceData)
                    .then(response => {
                        this.imageLoading = false;
                        const data = response.data;

                        if (data.code === 200) {
                            alert('人脸注册成功！');
                            this.closeFaceRegisterModal();
                            // 更新用户信息中的faceRegister状态
                            this.user.faceRegister = 1;
                        } else {
                            this.imageError = data.message || '人脸注册失败，请重试';
                        }
                    })
                    .catch(error => {
                        this.imageLoading = false;
                        console.error('人脸注册失败', error);
                        this.imageError = '注册失败，请稍后重试';
                    });
                },

                // ========== 拍照相关方法 ==========

                // 启动摄像头
                startCamera: function () {
                    this.cameraLoading = true;
                    this.imageError = '';

                    // 检查浏览器是否支持getUserMedia
                    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                        this.imageError = '您的浏览器不支持拍照功能，请使用上传图片方式';
                        this.cameraLoading = false;
                        return;
                    }

                    // 获取摄像头权限和视频流
                    navigator.mediaDevices.getUserMedia({
                        video: {
                            width: { ideal: 640 },
                            height: { ideal: 480 },
                            facingMode: 'user' // 优先使用前置摄像头
                        }
                    })
                    .then(stream => {
                        this.cameraStream = stream;
                        this.cameraLoading = false;
                        this.showCamera = true;

                        // 将视频流显示到video元素
                        this.$nextTick(() => {
                            const video = document.getElementById('cameraVideo');
                            if (video) {
                                video.srcObject = stream;
                                video.onloadedmetadata = () => {
                                    video.play();
                                };
                                video.onerror = (err) => {
                                    this.imageError = '视频播放错误';
                                };
                            }
                        });
                    })
                    .catch(error => {
                        this.cameraLoading = false;
                        if (error.name === 'NotAllowedError') {
                            this.imageError = '摄像头权限被拒绝，请在浏览器设置中允许访问摄像头';
                        } else if (error.name === 'NotFoundError') {
                            this.imageError = '未找到摄像头设备';
                        } else {
                            this.imageError = '无法访问摄像头';
                        }
                    });
                },

                // 停止摄像头
                stopCamera: function () {
                    if (this.cameraStream) {
                        // 停止所有视频流
                        this.cameraStream.getTracks().forEach(track => {
                            track.stop();
                        });
                        this.cameraStream = null;
                    }

                    this.showCamera = false;
                },

                // 拍照
                capturePhoto: function () {
                    if (!this.cameraStream) {
                        this.imageError = '摄像头未启动';
                        return;
                    }

                    const video = document.getElementById('cameraVideo');
                    const canvas = document.createElement('canvas');
                    const context = canvas.getContext('2d');

                    // 设置canvas尺寸与视频尺寸一致
                    canvas.width = video.videoWidth;
                    canvas.height = video.videoHeight;

                    // 将当前视频帧绘制到canvas
                    context.drawImage(video, 0, 0, canvas.width, canvas.height);

                    // 转换为Base64格式，去掉data:image/jpeg;base64,前缀
                    const dataURL = canvas.toDataURL('image/jpeg', 0.8);
                    this.faceImage = dataURL.split(',')[1];

                    // 停止摄像头
                    this.stopCamera();

                    // 清空文件输入
                    document.getElementById('faceImageInput').value = '';
                },

                // 选择图片方式
                selectImage: function () {
                    this.stopCamera();
                    document.getElementById('faceImageInput').click();
                }
            }
        });

        // 将Vue实例暴露到全局，方便调试
        window.app = app;
    });
</script>
</body>
</html>
